'use strict';
var entityCollection = require('./EntityCollection');

var relation = {
	//CBO
	ItemMaster: {
		BarcodeMaster: ['ItemMaster'],
		Routing: ['ItemMaster'],
		MO: ['ItemMaster'],
		RcvRecord: ['ItemMaster'],
		QCStandard: ['ItemMaster']
	},
	Container: {
		DeliveryRecord: ['Container'],
		RcvRecord: ['Container']
	},
	Department: {
		WorkLocation: ['Department'],
		User: ['Department'],
		Department: ['ParentDepartment'],
		WareHouse: ['Department']
	},
	Operation: {
		BarcodeMaster: ['Operation', 'QCReworkOperation'],
		BizRecord: ['Operation'],
		RcvRecord: ['RcvOperation']
	},
	Terminal: {
		BarcodeMaster: ['Terminal'],
		BizRecord: ['Terminal'],
		StationTerminal: ['Terminal'],
		StationUser: ['Terminal']
	},
	WareHouse: {
		DeliveryRecord: ['WareHouse'],
		KanbanDemand: ['WareHouse'],
		RcvRecord: ['WareHouse']
	},
	Work: {
		BarcodeMaster: ['Work'],
		BizRecord: ['Work'],
		Operation: ['Work'],
		StationWork: ['Work'],
		QCStandard: ['Work']
	},
	WorkLocation: {
		BarcodeMaster: ['WorkLocation'],
		BizRecord: ['WorkLocation'],
		StationTerminal: ['WorkLocation'],
		StationUser: ['WorkLocation'],
		StationWork: ['WorkLocation']
	},

	//Barcode
	AssemblyRelation: {
		BarcodeMaster: ['AssemblyRelation']
	},
	BarcodeMaster: {
		AssemblyRelation: ['BarcodeMaster', 'AssemblyBarcode'],
		BizRecord: ['BarcodeMaster'],
		RcvRecord: ['BarcodeMaster']
	},
	BizRecord: {
		BarcodeMaster: ['BizRecord'],
		RcvRecord: ['BizRecord'],
		QCRecord: ['BizRecord']
	},

	//ProductReady
	MO: {
		BarcodeMaster: ['MO'],
		KanbanDemand: ['MO']
	},

	//ProductWork
	CompletePlan: {
		BarcodeMaster: ['CompletePlan']
	},

	//QC
	QCNorm: {
		BadTypeBind: ['QCNorm'],
		QCRecord: ['QCNorm'],
		QCStandard: ['QCNorm']
	},
	QCStandard: {
		QCRecord: ['QCStandard']
	},

	//SystemManage
	App: {
		AppRole: ['Apps']
	},
	AppRole: {
		User: ['AppRoles']
	},
	Menu: {
		Menu: ['Parent'],
		Role: ['Menus']
	},
	Role: {
		User: ['Roles']
	},
	ExtendEnum: {
		QCNorm: ['ExtendEnum']
	},
	User: {
		BarcodeMaster: ['Users'],
		StationUser: ['User'],
		DeliveryRecord: ['StockPerson', 'ReceivePerson'],
		RcvRecord: ['RcvUser'],
		BizRecord: ['Users']
	}
};

//entityName： 实体名称
//condition：删除条件
exports.deleteVerify = function(entityName, condition, resultHandel){
	if (relation.hasOwnProperty(entityName)) {
		var self = this;
		var entity = entityCollection.getEntity(entityName);
		entity.find(condition, null, null, function(err, deleteRecords){
			if(err){
				resultHandel(err);
			}
			else{
				if(deleteRecords.length == 0){
					resultHandel();
				}
				else{
					var errors = [];
					var references = [];	//被引用的实体记录

					var ids = [];
					for(var i=0; i<deleteRecords.length; i++){
						ids.push(deleteRecords[i]._id);
					}
					var refEntityNameCount = 0;

					for(var refEntityName in relation[entityName]){
						refEntityNameCount++;

						var condition = {$or: []};
				        for(var j=0; j<relation[entityName][refEntityName].length; j++){
				            var filedCondition = {};
				            filedCondition[relation[entityName][refEntityName][j]] = {$in: ids};
				            condition['$or'].push(filedCondition);
				        }
				        
				        var refEntity = entityCollection.getEntity(refEntityName);
				        refEntity.findOne(condition, null, function(err, refRecord){
				        	refEntityNameCount--;

				        	if(err){
								errors.push(err);
							}
							else{
								if(refRecord != null){
									references.push({EntityName: refRecord.collection.name, Record: refRecord});
								}
							}

							if(refEntityNameCount == 0){
								if(errors.length == 0 && references.length == 0){
									resultHandel();
								}
								else{
									if(errors.length > 0){
										resultHandel(errors[0]);
									}
									else{
										resultHandel({
											level: 5,
											title: '删除失败',
											message: entityCollection.getEntity(entityName).Name + " 被 " + entityCollection.getEntity(references[0].EntityName).Name + " 引用，不能删除"
										});
									}
								}
							}
				        });
					}
				}
			}
		});
	}
	else{
		resultHandel();
	}
};
